(define (filtered-accumulate combiner filter null-value term a next b)
    (define (iter a result)
        (cond   ((> a b) result)
                ((filter a)
                    (iter (next a) (combiner (term a) result)))
                (else
                    (iter (next a) result))))
    (iter a null-value))

; 测试用过程
(define combiner +)
(define (term n) n)
(define (next n) (+ n 1))

; 求 a、b之间偶数之和
(define (even-sum a b)
    (filtered-accumulate combiner even? 0 term a next b))

; 求 a、b 之间的素数之和
(define (prime-sum a b)
    (define (prime? n)
        (define (iter n i)
            (cond ((= n 1) false)
                  ((> (square i) n) true)
                  ((= (remainder n i) 0) false)
                  (else (iter n (+ i 1)))))
        (iter n 2))
    (filtered-accumulate combiner prime? 0 term a next b))

; 求小于 n 与 n 素质的正整数之积
(define (gcd-sum n)
    (define (gcd a b)
        (if (= b 0)
            a
            (gcd b (remainder a b))))
    (define (filter i)
        (if (= (gcd i n) 1)
            true
            false))
    (define combiner *)
    (filtered-accumulate combiner filter 1 term 1 next n))

(display "\n========================================\n")
(display (even-sum 0 10))
(newline)
(display (prime-sum 0 10))
(newline)
(display (gcd 4 10))
(newline)
(display (gcd-sum 6))
(display "\n========================================\n")
